<?php

	class db_connection extends PDO{
		
		private $__profile = array();
		
		public function __construct($db_cfg){

			parent::__construct(
				"mysql:host={$db_cfg["host"]};dbname={$db_cfg["base"]};charset=UTF-8",
				$db_cfg["login"],
				$db_cfg["pass"]
			);
			
			$this->query("SET NAMES utf8");

		}
		
		public function db_query($query){
			//$this->execute($query);	//?
			
			$this->query($query);
			$this->log_error();
		}
		
		public function fetch_table($table_name){
			$query = "SELECT * FROM {$table_name}";
			return $this->fetch_array($query);
		}
		
		public function fetch_table_row($table_name, $value, $key = "id"){
			return $this->fetch_one("SELECT * FROM {$table_name} WHERE `{$key}` = '{$value}'");
			
			$this->log_error();
		}
		
		public function log_error(){
			$error = PDO::errorInfo();
			if ((int)$error[0]){
				#context::get("io")->trace();
				print_r($error);
			}
		}
		
		public function fetch_array($query){

			context::get("timer")->push();
			$__query = $this->query($query);
			
			$this->log_error();
			
			if ($__query){
				$result = $__query->fetchAll(PDO::FETCH_ASSOC);
				$this->__profile[] = array("query"=>$query, "time"=>context::get("timer")->pop());

				return $result; 
			}
			
			return null;
		}
		
		public function fetch_one($query){
			$arr = $this->fetch_array($query);
			return $arr[0];
		}
		
		private function execute($query){
			$res = $this->prepare($query);
			$res->execute($query);

			return $res;
		}
		
		public function profile(){
			foreach($this->__profile as $query){
				$total_time += $query["time"];
			}
			
			return array("count"=>sizeof($this->__profile),"time"=>sprintf("%.2f",$total_time));
		}
	}

	class db extends service {
		
		private $__connections;
		
		public function __call($name, $args){
			if ($db = $this->get_instance("default")){
				if (is_callable(array($db,$name))){
					return call_user_func_array(array($db,$name),$args);
				}else{
					context::get("io")->debug("failed to call db::{$name}");
					return null;
				}
			}
		}
		
		
		private function get_instance($db_name){
			
			if (isset($this->__connections[$db_name])){
				return $this->__connections[$db_name];
			}else{
			
				$cfg = context::get("config");
				
				if (isset($cfg["db"][$db_name])){
					$db_cfg = $cfg["db"][$db_name];
					$db = new db_connection($db_cfg);
					
					$this->__connections[$db_name] = $db;
					
					return $db;
					
				}else{
					#throw new Core_Exception("unable to create instance of '{$db_name}' db connection, empty config section", EX_NONCRIT);
					return null;
				}
			}
		}
		
		
	}

?>
